'use strict';

const { Service } = require('egg');
const https = require('https');

class NewsService extends Service {
  getNewsList(force) {
    const { ctx } = this;
    if (!ctx.app.data || ctx.app.expire <= new Date() || force) {
      return ctx.service.token.getToken().then(token => {
        return new Promise((resolve, reject) => {
          const data = JSON.stringify({
            type: 'news',
            offset: 0,
            count: 20,
          });
          const request = https.request('https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=' + encodeURIComponent(token), {
            method: 'post',
            headers: {
              'Content-Type': 'application/json',
              Connection: 'keep-alive',
              'Content-Length': data.length,
            },
          }, res => {
            if (res.statusCode === 200) {
              let data = '';
              res.on('data', chunk => { data += chunk; });
              res.on('end', () => {
                resolve(JSON.parse(data));
              });
            } else {
              reject(new Error('HTTP ' + res.statusCode));
            }
          });
          request.on('error', err => {
            reject(err);
          });
          request.write(data, error => {
            if (error) {
              reject(error);
            }
          });
          request.end();
        });
      });
    }

    return new Promise(resolve => resolve(ctx.app.data));
  }

  search(word) {
    return this.getNewsList().then(value => {
      return new Promise(resolve => {
        let result = '';
        let count = 0;
        for (const item of value.item) {
          for (const article of item.content.news_item) {
            if (article.title.indexOf(word) !== -1) {
              if (count !== 0) result += '\n';
              result += '[' + (++count).toString() + '] ' + article.title + '\n' + article.url;
            }
          }
        }
        if (result === '') result = '未找到文章';
        resolve(result);
      });
    });
  }

  pick(date) {
    return this.getNewsList().then(value => {
      return new Promise(resolve => {
        let result = '';
        let count = 0;
        for (const item of value.item) {
          const dt = new Date(item.update_time * 1000);
          if (dt.getFullYear() !== date.getFullYear() || dt.getMonth() !== date.getMonth() || dt.getDate() !== date.getDate()) continue;
          for (const article of item.content.news_item) {
            if (count !== 0) result += '\n';
            result += '[' + (++count).toString() + '] ' + article.title + '\n' + article.url;
          }
        }
        if (result === '') result = '未找到文章';
        resolve(result);
      });
    });
  }
}

module.exports = NewsService;
